﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Framework.Library;
using Framework.Library.Components.Commands;
using Framework.Library.Components.Roles;
using Framework.Library.Components.Security;
using Framework.Library.Components.Portal;
using Framework.Library.Utilities;

namespace Portal.Administrator.Roles
{
	public partial class RolePermision : AuthenticatedControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            if ((!CurrentUser.IsSuperAdmin && CommandController.IsSystemModule(AppEnv.CommandID())) || !CommandController.IsAvailableForUser(AppEnv.CommandID(), CurrentUser.UserID, Convert.ToInt32(AppEnv.PortalId())))
                Response.Redirect(AppEnv.ADMIN_CMD, true);
			if (!Page.IsPostBack)
			{
                LoadPortal();
                LoadCommand();
                lblCommandName.Text = AppEnv.CommandName();
			}
		}

        public void LoadPortal()
        {
            //Fill portals
            dropPortal.Items.Clear();
            PortalController.LoadPortalsForUserID(dropPortal.Items, CurrentUser.UserID);
            dropPortal.SelectedValue = AppEnv.PortalId();
        }

        public void LoadCommand()
        {   
            //Fill roles	
            rdoRoles.Items.Clear();
            RoleController.LoadRoles(rdoRoles.Items);            
            BindData();
        }
        
        public void BindData()
        {
            //Fill commands
            lstCommands.Items.Clear();
            CommandController.FillToListBox(lstCommands.Items, CommandController.GetCommands(), CurrentUser.IsSuperAdmin);
            CommandSelected();
        }
        protected void dgrRolePermission_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "edit")
            {
                int role_id = ConvertUtility.ToInt32(e.Item.Cells[0].Text);
                int command_id = ConvertUtility.ToInt32(e.Item.Cells[1].Text);
                int portal_id = ConvertUtility.ToInt32(e.Item.Cells[2].Text);
                CheckBox chkView = (CheckBox)e.Item.FindControl("chkView");
                CheckBox chkAdd = (CheckBox)e.Item.FindControl("chkAdd");
                CheckBox chkUpdate = (CheckBox)e.Item.FindControl("chkEdit");
                CheckBox chkDelete = (CheckBox)e.Item.FindControl("chkDelete");
                try
                {                    
                    RoleController.UpdateRolePermissionByPortalID(role_id, command_id, portal_id, chkView.Checked, chkAdd.Checked, chkUpdate.Checked, chkDelete.Checked);
                    int roleId = ConvertUtility.ToInt32(rdoRoles.SelectedValue);
                    DataTable dtCommands = CommandController.GetCommandsForRoleByPortalID(roleId, ConvertUtility.ToInt32(dropPortal.SelectedValue));
                    LoadCommandInfo(dtCommands, roleId);
                    lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                }
                catch (Exception ex)
                {
                    lblUpdateStatus.Text = ex.Message;
                }
            }
        }
        protected void dgrRolePermission_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemIndex < 0) return;

            DataRowView row = (DataRowView)e.Item.DataItem;

            Label lblCmdName = (Label)e.Item.FindControl("lblCmdName");
            lblCmdName.Text = row["CommandName"].ToString();

            CheckBox chkView = (CheckBox)e.Item.FindControl("chkView");
            CheckBox chkAdd = (CheckBox)e.Item.FindControl("chkAdd");
            CheckBox chkEdit = (CheckBox)e.Item.FindControl("chkEdit");
            CheckBox chkDelete = (CheckBox)e.Item.FindControl("chkDelete");
            ImageButton btnUpdate = (ImageButton)e.Item.FindControl("btnUpdate");

            if (!String.IsNullOrEmpty(row["CommandKey"].ToString()))
            {
                chkView.Checked = ConvertUtility.ToBoolean(row["Role_View"].ToString());
                chkAdd.Checked = ConvertUtility.ToBoolean(row["Role_Add"].ToString());
                chkEdit.Checked = ConvertUtility.ToBoolean(row["Role_Update"].ToString());
                chkDelete.Checked = ConvertUtility.ToBoolean(row["Role_Delete"].ToString());
            }
            else
            {
                chkAdd.Visible = false;
                chkDelete.Visible = false;
                chkEdit.Visible = false;
                chkView.Visible = false;
                btnUpdate.Visible = false;
            }            
        }
		
        protected void btnUpdate_Click(object sender, EventArgs e)
		{
			try
			{
				int roleId = ConvertUtility.ToInt32(rdoRoles.SelectedValue);
				foreach (ListItem item in lstCommands.Items)
				{
					if (item.Selected)
					{
                        RoleController.AddCommandToRoleByPortalID(Convert.ToInt32(item.Value), roleId,ConvertUtility.ToInt32(dropPortal.SelectedValue));
					}
					else
					{
                        RoleController.RemoveCommandFromRoleByPortalID(Convert.ToInt32(item.Value), roleId, ConvertUtility.ToInt32(dropPortal.SelectedValue));
					}
				}
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                BindData();
			}
			catch (Exception ex)
			{
				Response.Write(ex.Message);
			}
		}

        private void CommandSelected()
        {
            int roleId = ConvertUtility.ToInt32(rdoRoles.SelectedValue);
            DataTable dtCommands = CommandController.GetCommandsForRoleByPortalID(roleId, ConvertUtility.ToInt32(dropPortal.SelectedValue));
            foreach (ListItem item in lstCommands.Items)
            {
                if (dtCommands.Select("CommandID = " + item.Value).Length > 0)
                {
                    item.Selected = true;
                }
                else
                {
                    item.Selected = false;
                }
            }
            LoadCommandInfo(dtCommands, roleId);
        }

        private void LoadCommandInfo(DataTable dtCommands, int roleId)
        {
            DataTable dtReturnCommand = new DataTable();
            dtReturnCommand.Columns.Add("CommandID", typeof(String));
            dtReturnCommand.Columns.Add("CommandKey", typeof(String));
            dtReturnCommand.Columns.Add("PortalID", typeof(String));
            dtReturnCommand.Columns.Add("RoleID", typeof(String));
            dtReturnCommand.Columns.Add("CommandParentID", typeof(String));
            dtReturnCommand.Columns.Add("CommandName", typeof(String));
            dtReturnCommand.Columns.Add("Level", typeof(String));
            dtReturnCommand.Columns.Add("Role_View", typeof(String));
            dtReturnCommand.Columns.Add("Role_Add", typeof(String));
            dtReturnCommand.Columns.Add("Role_Update", typeof(String));
            dtReturnCommand.Columns.Add("Role_Delete", typeof(String));

            DataTable _dtReturnCommand = RoleController.BuildRecursiveRolePermission(dtCommands, dtReturnCommand, roleId, ConvertUtility.ToInt32(dropPortal.SelectedValue));
            dgrRolePermission.DataSource = _dtReturnCommand;
            dgrRolePermission.ItemDataBound += new DataGridItemEventHandler(dgrRolePermission_ItemDataBound);
            dgrRolePermission.DataBind();
        }

		protected void rdoRoles_SelectedIndexChanged(object sender, EventArgs e)
		{
            BindData();
		}

        protected void btnUpdateAll_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridItem item in dgrRolePermission.Items)
                {
                    int role_id = ConvertUtility.ToInt32(item.Cells[0].Text);
                    int command_id = ConvertUtility.ToInt32(item.Cells[1].Text);
                    int portal_id = ConvertUtility.ToInt32(item.Cells[2].Text);
                    CheckBox chkView = (CheckBox)item.FindControl("chkView");
                    CheckBox chkAdd = (CheckBox)item.FindControl("chkAdd");
                    CheckBox chkUpdate = (CheckBox)item.FindControl("chkEdit");
                    CheckBox chkDelete = (CheckBox)item.FindControl("chkDelete");                    
                    RoleController.UpdateRolePermissionByPortalID(role_id, command_id, portal_id, chkView.Checked, chkAdd.Checked, chkUpdate.Checked, chkDelete.Checked);                    
                }
                int roleId = ConvertUtility.ToInt32(rdoRoles.SelectedValue);
                DataTable dtCommands = CommandController.GetCommandsForRoleByPortalID(roleId, ConvertUtility.ToInt32(dropPortal.SelectedValue));
                LoadCommandInfo(dtCommands, roleId);

                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;                
            }
            catch
            {
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_ERROR;
            }
        }

        protected void dropPortal_SelectedIndexChanged(object sender, EventArgs e)
        {            
            BindData();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            lstCommands.SelectedIndex = -1;
        }
	}
}